package com.boot.study.listener;

import com.alibaba.fastjson.JSON;
import com.github.shyiko.mysql.binlog.BinaryLogClient;
import com.github.shyiko.mysql.binlog.event.*;
import com.github.shyiko.mysql.binlog.event.deserialization.EventDeserializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @Author: lkz
 * @Title: MysqlEventListener
 * @Description: TODO
 * @Date: 2023/9/22 10:38
 * 参考 https://www.jianshu.com/p/3c150d1aa555
 * 另一种方式 https://blog.csdn.net/m0_37583655/article/details/119148470
 */
@Component
@Slf4j
public class MysqlEventListener implements ApplicationRunner {


    @Override
    public void run(ApplicationArguments args) throws Exception {
        BinaryLogClient client = new BinaryLogClient("106.14.221.87", 3306, "root", "lkz123456");
        EventDeserializer eventDeserializer = new EventDeserializer();
//        eventDeserializer.setCompatibilityMode(
//                EventDeserializer.CompatibilityMode.DATE_AND_TIME_AS_LONG,
//                EventDeserializer.CompatibilityMode.CHAR_AND_BINARY_AS_BYTE_ARRAY
//        );
        client.setEventDeserializer(eventDeserializer);

        // 数据监听
        client.registerEventListener(event -> {
            EventData data = event.getData();
            EventType eventType = event.getHeader().getEventType();
            if (data instanceof TableMapEventData) {
                TableMapEventData tableMapEventData = (TableMapEventData) data;
                System.err.println("db：" + tableMapEventData.getDatabase());
                System.err.println("tableName：" + tableMapEventData.getTable());

            }



            // 表数据修改
            if (data instanceof UpdateRowsEventData) {

                log.info("update: [{}]", JSON.toJSONString(data));
            } else if (data instanceof WriteRowsEventData) {
                log.info("insert: [{}]", data);
            } else if (data instanceof DeleteRowsEventData) {
                log.info("delete: [{}]", data);
            }

        });
        client.connect();
    }

}
